import os
from quant_researcher.quant.datasource_fetch.crypto_api.coingecko import CoinGeckoAPI
from quant_researcher.quant.project_tool.time_tool import date_shifter
import time
import pandas as pd
from utils import df_into_db


### 从coingecko获取主流交易所现货交易额历史数据 ###
DATA_DIR = f'E:\\指标数据'  # 用于存放测试数据

file_path = os.path.join(DATA_DIR, r'trading_data')
cg = CoinGeckoAPI()
spot_exchange_id_list = ['binance', 'gdax', 'okex', 'huobi', 'gate', 'kucoin', 'crypto_com', 'bitfinex', 'bybit_spot']
exchange_volume_df_list = []
file_name = os.path.join(file_path, f'cex_total_spot_amount_each_exchange_coingecko')
if os.path.exists(f'{file_name}.xlsx'):
    days = 30
else:
    days = 365
for exchange_id in spot_exchange_id_list:
    print(f'开始获取{exchange_id}现货交易额数据')
    exchange_volume = cg.get_exchanges_volume_chart_by_id(id=exchange_id, days=days)['amount']
    print(f'{exchange_id}现货交易额数据获取成功')
    if exchange_id == 'gdax':
        exchange_name = 'coinbase'
    elif exchange_id == 'ftx_spot':
        exchange_name = 'ftx'
    else:
        exchange_name = exchange_id
    exchange_volume = exchange_volume[~exchange_volume.index.duplicated(keep="first")]
    exchange_volume.name = exchange_name
    exchange_volume_df_list.append(exchange_volume)
    time.sleep(10)

spot_exchange_volume_df = pd.concat(exchange_volume_df_list, axis=1)
if os.path.exists(f'{file_name}.xlsx'):
    hist_spot_exchange_volume_df = pd.read_excel(f'{file_name}.xlsx', index_col='date')
    previous_date = date_shifter(spot_exchange_volume_df.index[0], step='days', how_many=-1)
    spot_exchange_volume_df = pd.concat \
        ([hist_spot_exchange_volume_df.loc[:previous_date, ], spot_exchange_volume_df.iloc[:-1, ]])  # 最新一天数据为当天，数据还不完整
spot_exchange_volume_df.fillna(0, inplace=True)
spot_exchange_volume_df = spot_exchange_volume_df.reset_index(drop=False)
df_into_db(spot_exchange_volume_df, db_name='trading_data', table_name='cex_total_spot_amount_each_exchange_coingecko')